<template>
  <div class="detail-container">
    <!-- 头部导航 -->
    <div class="header">
      <van-nav-bar title="商品详情" left-text="返回" left-arrow @click-left="$router.back()"></van-nav-bar>
    </div>
    <!-- 商品主要信息 -->
    <div class="goods-info">
      <!-- 商品图片 -->
      <div class="goods-img">
        <van-image :src="'http://www.dsl2023hcy.love:3004' + goodsInfo.goods_img"> </van-image>
      </div>
      <!-- 商品标题 -->
      <div class="goods-title">
        {{ goodsInfo.goods_name }}
      </div>
      <!-- 商品价格以及销量 -->
      <div class="goods-price-sell">
        <div class="price">
          <span>￥</span>
          <span class="number">{{ getPriceInt }}</span>
          <span>.{{ getPriceFloat }}</span>
          <span>元</span>
        </div>
        <div class="sell">
          销量
          <span>{{ goodsInfo.goods_sell_num }}</span>
        </div>
        <!-- 后面考虑添加有多少人付款 -->
      </div>
    </div>
    <!-- 商品详情 -->
    <div class="goods-detail" v-if="goodsInfo.goods_desc">
      <div class="detail-title">商品详情</div>
      <div class="desc" v-html="goodsInfo.goods_desc"></div>
    </div>
    <!-- 加入购物车或者提交订单 -->
    <div class="add-shop-cart-submit-order">
      <!-- 加入购物车 -->
      <van-goods-action>
        <van-goods-action-icon icon="chat-o" text="客服" dot @click="$toast('~敬请期待~')" />
        <van-goods-action-icon icon="shopping-cart" text="购物车" color="#646566" v-if="shopCartCount == 0" @click="$router.push('/shopcart')" />
        <van-goods-action-icon icon="shopping-cart" text="购物车" color="#646566" :badge="shopCartCount" v-else @click="$router.push('/shopcart')" />

        <van-goods-action-icon icon="star" text="已收藏" color="#ee0a24" @click="toggleLikeState" v-if="isLike" />
        <van-goods-action-icon icon="star" text="收藏" color="#646566" @click="toggleLikeState" v-else />
        <van-goods-action-button type="warning" text="加入购物车" @click="showAddCartForm = true" />
        <van-goods-action-button type="danger" text="立即购买" @click="showSubmitForm = true" />
      </van-goods-action>
    </div>
    <!-- 添加购物车弹出层 -->
    <van-popup v-model="showAddCartForm" position="bottom" round closeable>
      <div class="content">
        <div class="goods-content">
          <div class="goods-img">
            <img :src="'http://www.dsl2023hcy.love:3004' + goodsInfo.goods_img" alt="" />
          </div>
          <div class="price-stock">
            <div class="price">
              <span>￥</span>
              <span class="number">{{ getPriceInt }}</span>
              <span>.{{ getPriceFloat }}</span>
            </div>
            <div class="stock">
              库存剩余量:{{ goodsInfo.goods_stock }}
              <span style="margin-left: 5px"
                ><van-tag :type="getTagType">{{ getTagText }}</van-tag></span
              >
            </div>
          </div>
        </div>
        <!-- 选择数量 -->
        <div class="goods-count">
          <div class="text">选择数量</div>
          <div class="step">
            <van-stepper v-model="cartCount" min="1" :max="goodsInfo.goods_stock" />
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="submit-btn">
          <van-button block color="#FF9318" round @click="addShopCart">加入购物车</van-button>
        </div>
      </div>
    </van-popup>
    <!-- 提交订单弹出层 -->
    <van-popup v-model="showSubmitForm" position="bottom" round closeable>
      <div class="content">
        <div class="goods-content">
          <div class="goods-img">
            <img :src="'http://www.dsl2023hcy.love:3004' + goodsInfo.goods_img" alt="" />
          </div>
          <div class="price-stock">
            <div class="price">
              <span>￥</span>
              <span class="number">{{ getPriceInt }}</span>
              <span>.{{ getPriceFloat }}</span>
            </div>
            <div class="stock">
              库存剩余量:{{ goodsInfo.goods_stock }}
              <span style="margin-left: 5px"
                ><van-tag :type="getTagType">{{ getTagText }}</van-tag></span
              >
            </div>
          </div>
        </div>
        <!-- 选择收货地址 -->
        <div class="address">
          <van-cell is-link @click="selectAddress">
            <template #icon>
              <div class="icon">
                <van-icon name="location" />
              </div>
            </template>
            <template #title>
              <div class="address-content">
                <div class="address-detail">{{ address }}</div>
                <div class="name-phone">
                  <div class="name">{{ name }}</div>
                  <div class="phone">{{ phone }}</div>
                </div>
              </div>
            </template>
          </van-cell>
        </div>
        <!-- 选择数量 -->
        <div class="goods-count">
          <div class="text">选择数量</div>
          <div class="step">
            <van-stepper v-model="orderCount" min="1" :max="goodsInfo.goods_stock" />
          </div>
        </div>
        <!-- 订单备注 -->
        <div class="order-remark">
          <van-field v-model="message" rows="2" autosize label="备注：" type="textarea" maxlength="128" placeholder="请输入备注..." show-word-limit />
        </div>
        <!-- 提交按钮 -->
        <div class="submit-btn">
          <van-button block color="#ee0a24" round @click="addOrder">提交订单</van-button>
        </div>
      </div>
    </van-popup>
    <!-- 地址选择 -->
    <van-popup v-model="show" position="bottom" round closeable>
      <SelectAddress
        @setChosenAddressId="
          (val) => {
            chosenAddressId = val
          }
        "
        @editUserInfo="setUserNamePhone"
      ></SelectAddress>
    </van-popup>
  </div>
</template>

<script>
import axios from '@/utils/request/request'
import SelectAddress from '../user/order/SelectAddress.vue'
import { Notify } from 'vant'
export default {
  name: 'goodsDetail',
  data() {
    return {
      id: '',
      goodsInfo: {},
      shopCartCount: 0,
      isLike: false,
      showAddCartForm: false,
      showSubmitForm: false,
      orderCount: 1,
      cartCount: 1,
      address: '',
      name: '',
      phone: '',
      like_id: 0,
      message: '',
      show: false,
      chosenAddressId: ''
    }
  },
  components: {
    SelectAddress
  },
  computed: {
    // 获取价格整数部分
    getPriceInt() {
      return parseFloat(this.goodsInfo.goods_price).toFixed(2).split('.')[0]
    },
    // 获取价格小数部分
    getPriceFloat() {
      return parseFloat(this.goodsInfo.goods_price).toFixed(2).split('.')[1]
    },
    // 标签类型
    getTagType() {
      let tagType = ''
      if (this.goodsInfo.goods_stock >= 100) {
        tagType = 'success'
      } else if (this.goodsInfo.goods_stock < 100 && this.goodsInfo.goods_stock > 0) {
        tagType = 'warning'
      } else {
        tagType = 'danger'
      }
      return tagType
    },
    // 标签文字
    getTagText() {
      let text = ''
      if (this.goodsInfo.goods_stock >= 100) {
        text = '库存充足'
      } else if (this.goodsInfo.goods_stock < 100 && this.goodsInfo.goods_stock > 0) {
        text = '库存紧张'
      } else {
        text = '缺货'
      }
      return text
    }
  },
  methods: {
    selectAddress() {
      this.show = true
      this.getAllAddress()
    },
    setUserNamePhone({ addressDetail, name, tel }) {
      this.address = addressDetail
      this.name = name
      this.phone = tel
      this.show = false
    },
    // 获取商品详情数据
    async getGoodsDetail() {
      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      try {
        const data = await axios.get('/api/user/goods/detail/' + this.id)

        if (data.code === 0) {
          // 获取数据成功
          this.goodsInfo = { ...data.data }
        } else {
          Notify({
            type: 'danger',
            message: data.msg
          })
        }
      } catch {
        Notify({
          type: 'danger',
          message: '获取商品详情信息失败!',
          duration: 500
        })
      } finally {
        this.$toast.clear()
      }
    },
    // 获取商品收藏信息
    async getGoodsCollection() {
      try {
        const data = await axios.get('/user/goods/collection', {
          params: {
            id: this.id
          }
        })
        if (data.code === 0 && data.data) {
          this.like_id = data.data.id
          this.isLike = true
        }
      } catch {
        Notify({
          type: 'danger',
          message: '获取商品收藏信息失败!',
          duration: 500
        })
      }
    },
    // 切换收藏状态
    async toggleLikeState() {
      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      if (this.isLike) {
        try {
          // 取消收藏
          const data = await axios.post('/user/cancel/like', {
            id: this.like_id
          })

          if (data.code === 0) {
            this.isLike = false
            Notify({
              type: 'success',
              message: data.msg,
              duration: 500
            })
          } else if (data.code === 403 || data.msg === '身份认证错误') {
            Notify({
              type: 'danger',
              message: data.msg,
              duration: 1000,
              onClose: () => {
                localStorage.removeItem('user_token')
                this.$router.push('/login')
              }
            })
          } else {
            Notify({
              type: 'danger',
              message: data.msg,
              duration: 500
            })
          }
        } catch {
          Notify({
            type: 'danger',
            message: '取消收藏失败!',
            duration: 500
          })
        } finally {
          this.$toast.clear()
        }
      } else {
        try {
          // 收藏
          const data = await axios.post('/user/add/like', {
            id: this.id
          })
          if (data.code === 0) {
            this.isLike = true
            Notify({
              type: 'success',
              message: data.msg,
              duration: 500
            })
            this.getGoodsCollection()
          } else if (data.code === 403 || data.msg === '身份认证错误') {
            Notify({
              type: 'danger',
              message: data.msg,
              duration: 1000,
              onClose: () => {
                localStorage.removeItem('user_token')
                this.$router.push('/login')
              }
            })
          } else {
            Notify({
              type: 'danger',
              message: data.msg,
              duration: 500
            })
          }
        } catch {
          Notify({
            type: 'danger',
            message: '收藏失败!',
            duration: 500
          })
        } finally {
          this.$toast.clear()
        }
      }
    },
    // 添加购物车
    async addShopCart() {
      if (this.cartCount < 1)
        return Notify({
          type: 'warning',
          message: '至少添加一件商品！'
        })
      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      try {
        const data = await axios.post('/user/add/cart', { id: this.id, count: this.cartCount })

        if (data.code === 0) {
          // 添加成功
          Notify({
            type: 'success',
            message: data.msg,
            duration: 500
          })
          // 重新获取购物车数量
          this.cartCount = 1
          this.showAddCartForm = false
          this.getAllCartGoods()
        } else if (data.code === 403 || data.msg === '身份认证错误') {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000,
            onClose: () => {
              localStorage.removeItem('user_token')
              this.$router.push('/login')
            }
          })
        } else {
          Notify({
            type: 'danger',
            message: data.msg
          })
        }
      } catch {
        Notify({
          type: 'danger',
          message: '添加购物车请求失败!'
        })
      } finally {
        this.$toast.clear()
      }
    },
    // 创建订单
    async addOrder() {
      if (this.chosenAddressId === '')
        return Notify({
          type: 'danger',
          message: '请选择收货地地址！'
        })
      // 创建提交订单所需要的参数
      const params = {
        order_remark: this.message,
        goods_ids: JSON.stringify([{ id: JSON.parse(this.id), count: this.orderCount }]),
        address_id: this.chosenAddressId
      }

      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      try {
        const data = await axios.post('/user/submit/order', params)
        if (data.code === 0) {
          Notify({
            type: 'success',
            message: data.msg,
            duration: 1000,
            onClose: () => {
              this.$router.push('/order/payment/' + data.data.orderId)
            }
          })
        } else if (data.code === 403 || data.msg === '身份认证失败！') {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000,
            onClose: () => {
              localStorage.removeItem('user_token')
              this.$router.push('/login')
            }
          })
        } else {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 2000
          })
        }
      } catch (err) {
        Notify({
          type: 'danger',
          message: err
        })
      } finally {
        this.$toast.clear()
      }
    },
    // 获取收货地址
    async getAllAddress() {
      try {
        const data = await axios.get('/user/address/list')
        if (data.code === 0) {
          // 默认选中默认地址
          this.addressList = data.data.map((item) => {
            if (item.status === 1) {
              this.chosenAddressId = item.id
              this.address = item.address
              this.name = item.name
              this.phone = item.phone
              return {
                id: item.id,
                tel: item.phone,
                name: item.name,
                address: item.province + item.city + item.country + item.address,
                addressDetail: item.address,
                isDefault: true
              }
            } else {
              return {
                id: item.id,
                tel: item.phone,
                name: item.name,
                address: item.province + item.city + item.country + item.address,
                addressDetail: item.address,
                isDefault: false
              }
            }
          })
        } else if (data.msg === '身份认证错误' || data.code === 403) {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000,
            onClose: () => {
              localStorage.removeItem('user_token')
              this.$router.push('/login')
            }
          })
        }
      } catch (err) {
        Notify({
          type: 'danger',
          message: '获取收货地址失败!'
        })
      }
    },
    // 获取购物车数量
    async getAllCartGoods() {
      try {
        const data = await axios.get('/user/cart/count')
        if (data.code === 0) {
          this.shopCartCount = data.data.count
        }
      } catch (err) {
        Notify({
          type: 'danger',
          message: '获取购物车数量失败!'
        })
      }
    }
  },
  created() {
    this.id = this.$route.params.id
    this.getGoodsDetail()
    this.getGoodsCollection()
    this.getAllCartGoods()
  }
}
</script>

<style lang="less" scoped>
.detail-container {
  padding-top: 46px;
  min-height: 100vh;
  padding-bottom: 60px;
  background-color: #f5f5f5;

  .header {
    position: fixed;
    top: 0;
    left: 0;
    height: 46px;
    border-bottom: 1px solid #f1f1f1;
    width: 100vw;
    z-index: 999;
  }
  ::v-deep .van-nav-bar .van-icon,
  ::v-deep .van-nav-bar__text {
    color: #323232;
  }

  ::v-deep .van-popup__close-icon {
    font-size: 16px;
  }

  .goods-info {
    background-color: #fff;

    ::v-deep .van-image {
      width: 100%;
      height: auto;
    }

    img {
      width: 100%;
      height: auto;
    }
    .goods-title {
      font-weight: 700;
      margin-top: 10px;
      line-height: 22px;
      overflow: hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 2;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      padding: 0 10px;
    }

    .goods-price-sell {
      margin-top: 10px;
      padding: 0 10px 20px;
      display: flex;
      justify-content: space-between;

      .price {
        color: #ee0a24;
        font-size: 14px;
        span {
          font-weight: 700;
        }
        .number {
          font-size: 18px;
        }
      }
      .sell {
        font-size: 14px;
        color: #323232;
        span {
          color: #ee0a24;
          font-weight: 700;
        }
      }
    }
  }

  .goods-detail {
    margin-top: 15px;
    background-color: #fff;
    padding: 10px;

    .detail-title {
      font-weight: 700;
      font-weight: 18px;
      padding-bottom: 10px;
    }
  }

  .add-shop-cart-submit-order {
    position: fixed;
    bottom: 0;
    left: 0;
    height: 50px;
    width: 100%;
  }

  .content {
    padding: 15px 0;
    position: relative;
    padding-bottom: 160px;
    background-color: #f1f1f1;

    .goods-content {
      display: flex;
      align-items: center;
      padding: 10px 15px;
      background-color: #fff;
      border-radius: 15px;

      .goods-img {
        width: 45px;
        padding: 2px;
        background-color: #e1e1e1;

        img {
          width: 100%;
          height: auto;
          border-radius: 5px;
        }
      }

      .price-stock {
        margin-left: 10px;

        .price {
          color: #ee0a24;

          span {
            font-weight: 700;
            font-size: 14px;
          }

          .number {
            font-size: 20px;
          }
        }

        .stock {
          font-size: 12px;
          margin-top: 5px;
        }
      }
    }

    .goods-count,
    .address {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 10px;
      padding: 10px 15px;
      background-color: #fff;
      border-radius: 10px;

      ::v-deep .van-cell {
        padding: 0;
        align-items: center;
      }

      .icon {
        color: #fff;
        background-image: linear-gradient(to right, #ff6034, #ee0a24);
        border-radius: 999px;
        padding: 0 5px;
        margin-right: 5px;
      }

      .address-content {
        .address-detail {
          color: #000;
          font-weight: 700;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 296px;
        }

        .name-phone {
          display: flex;
          align-items: center;

          .name {
            color: #323232;
            margin-right: 5px;
          }
          .phone {
            color: #777;
          }
        }
      }
    }

    .submit-btn {
      position: absolute;
      width: 100%;
      left: 0;
      bottom: 0;
      height: 46px;
      padding: 5px 10px;
      background-color: #fff;

      ::v-deep .van-button {
        height: 36px;
      }
    }
  }

  .order-remark {
    margin-top: 10px;
    ::v-deep .van-field__label {
      width: auto;
    }
  }
}
</style>
